<?php


error_reporting(E_ALL);
ini_set('display_errors', 1);
include "defines.php";

include "functions.php";
include "variables.php";

if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $client_ip = $_SERVER['REMOTE_ADDR'];
} else {
    $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}


log_message("---[NEW REQUEST]-[IP:$client_ip]---");
$section_return = 1; // speichert den rückgabewert von include, standardwert 1


/*
 * 	Laden der Section Page
 */


/*
 * Die Include-Datei muss eine return Anweisung enthalten mit folgenden
 * Werten:
 * - Bei normaler Ausführung
 *   Array('filename' => string, -- Dateiname vom Template
 *         'data' => Array())    -- Array mit Daten für das Template
 * - Bei einem Fehler
 *   string  -- Die Fehlermeldung die angezeigt werden soll.
 */
if (isset($_GET['section'], $sections[$_GET['section']])) {
    if (file_exists('includes/' . $sections[$_GET['section']] )) {
        $section_return = include 'includes/' . $sections[$_GET['section']];
        log_message(INDEX_TAG . SECTION_TAG . $sections[$_GET['section']]);
    } else {
        $section_return = "Include-Datei konnte nicht geladen werden: 'includes/" . $sections[$_GET['section']] . "'";
        log_message(INDEX_TAG . SECTION_TAG . $section_return);
    }
} else {
    // default bereich laden
    $section_return = include 'includes/' . $sections['china'];
    log_message(INDEX_TAG . SECTION_LOADING_DEF . $sections['china']);
}


// Laden des HTML-Kopfs
if (is_array($section_return) and isset($section_return['filename'], $section_return['data']) and
        is_string($section_return['filename']) and
        is_array($section_return['data'])) {

    log_message(INDEX_TAG . TPL_TAG . TPL_OK);

    if (file_exists($file = 'templates/' . $section_return['filename'])) {
        /**
         * Zurückgegebene Daten aus dem Template
         * @var array
         */
        $data = $section_return['data']; // speicher die Arraydaten in eine Variable $data
        // die dann im Template verwendet werden kann.
        include $file;
        unset($file);
    } else {
        $msg = 'Templatedatei "' . $file . '" ist nicht vorhanden.';
        unset($file);
        log_message(INDEX_TAG . TPL_TAG . $msg);
        $data['msg'] = $msg;
        include 'templates/msg_fail.tpl';
        unset($msg);
    }
} else if (is_string($section_return)) {
    $msg = $section_return;
    log_message(INDEX_TAG . TPL_TAG . $msg);
    $data['msg'] = $msg;
    include 'templates/msg_fail.tpl';
    unset($msg);
} else if (1 === $section_return) {
    $msg = TPL_RETURN_NA;
    log_message(INDEX_TAG . TPL_TAG . $msg);
    $data['msg'] = $msg;
    include 'templates/msg_fail.tpl';
    unset($msg);
} else {
    $msg = TPL_RETURN_FAIL;
    log_message(INDEX_TAG . TPL_TAG . $msg);
    $data['msg'] = $msg;
    include 'templates/msg_fail.tpl';
    unset($msg);
}
?>
